package com.uenpay.im.ui.old.activity.attendance;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.baidu.location.BDLocation;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.weight.listener.ShakeListener;
import com.qyx.android.weight.listener.ShakeListener.OnShakeListener;
import com.qyx.android.weight.utils.baidumap.BaiDuMapUtil;
import com.qyx.android.weight.utils.baidumap.IGetLocationListener;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.base.BaseActivity;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.map.LocationActivtiy;
import com.uenpay.im.callback.IPopupWindowListener;
import com.uenpay.im.entities.PopupEntity;
import com.uenpay.im.view.MyPopupWindow;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @author SL
 * @created 2016-3-12 下午10:04:57
 * @copyRight http://www.qiyunxin.com
 * @function 摇一摇签到
 */
public class ShakeSignActivity extends BaseActivity {

	private TextView fieldTv, signInTv, signOutTv;
	private ImageView fieldIv, signInIv, signOutIv;
	private MaskImageView position_iv;
	private TextView position_tv;
	private MediaPlayer BackgroundMediaPlayer;
	private String soundName = "";
	private ShakeListener mShakeListener = null;
	private Vibrator mVibrator;
	private AttendanceHandle mAttendanceHandle = new AttendanceHandle();
	private int entid = -1;
	private int type = 1;
	private double longitude, latitude;
	private ImageView success_iv;
	private MyPopupWindow myPopupWindow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shake_attend_layout);
		entid = getIntent().getIntExtra("entid", -1);
		initView();
		initListener();
		backListener();
		getLoaction();
	}

	private void initShake() {
		if (mVibrator == null) {
			mVibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
		}
		mShakeListener = new ShakeListener(this);
		mShakeListener.setOnShakeListener(new OnShakeListener() {

			@Override
			public void onShake() {
				if (latitude == 0.0 || longitude == 0.0) {
					IMApplication.showToast(R.string.address_error);
					return;
				}
				startShakeAnim();
				startVibrator();
				mShakeListener.stop();
				playSound("shake_sound_male.mp3", false);
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						attendance();
						playSound("shake_match.mp3", false);
						if (mShakeListener != null)
							mShakeListener.start();
					}
				}, 2000);
			}
		});
	}

	private void startVibrator() {
		mVibrator.vibrate(new long[] { 500, 200, 500, 200 }, -1);
	}

	private void startShakeAnim() {
		// shake_top
		Animation ani_shake_top = AnimationUtils.loadAnimation(this,
				R.anim.up_shaketop);
		((ImageView) findViewById(R.id.viewpager_shake_top))
				.startAnimation(ani_shake_top);
		// shake_bottom
		Animation ani_shake_bottom = AnimationUtils.loadAnimation(this,
				R.anim.down_shakebottom);
		((ImageView) findViewById(R.id.viewpager_shake_bottom))
				.startAnimation(ani_shake_bottom);
	}

	@Override
	protected void initView() {
		((TextView) findViewById(R.id.title_textview))
				.setText(R.string.shake_attend);
		success_iv = (ImageView) findViewById(R.id.success_iv);
		fieldTv = (TextView) findViewById(R.id.field_tv);
		signInTv = (TextView) findViewById(R.id.sign_in_tv);
		signOutTv = (TextView) findViewById(R.id.sign_out_tv);
		fieldIv = (ImageView) findViewById(R.id.field_iv);
		signOutIv = (ImageView) findViewById(R.id.sign_out_iv);
		signInIv = (ImageView) findViewById(R.id.sign_in_iv);
		position_iv = (MaskImageView) findViewById(R.id.position_iv);
		position_tv = (TextView) findViewById(R.id.position_tv);
		findViewById(R.id.title_right_iv_layout).setVisibility(View.VISIBLE);
		((ImageView) findViewById(R.id.title_right_iv))
				.setImageResource(R.drawable.icon_more);
		findViewById(R.id.position_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						ActivityHandle.startActivity(
								ShakeSignActivity.this,
								LocationActivtiy.class, null, 100);
					}
				});
		myPopupWindow = new MyPopupWindow(ShakeSignActivity.this, getPopData(),
				new IPopupWindowListener() {

					@Override
					public void itemClick(int index) {
						if (index == 2) {
							Bundle bundle = new Bundle();
							bundle.putInt("entid", entid);
							Utils.startActivity(ShakeSignActivity.this,
									ChooseAttendanceTypeActivity.class, bundle);
						} else if (index == 1) {
							Bundle bundle = new Bundle();
							bundle.putInt("entid", entid);
							Utils.startActivity(ShakeSignActivity.this,
									SetSignInTimeActivity.class, bundle);
						}
					}
				});
	}

	@Override
	protected void initListener() {
		findViewById(R.id.title_right_iv_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (myPopupWindow != null) {
							myPopupWindow.show(arg0);
						}
					}
				});
		findViewById(R.id.field_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						updateSelected(1);
					}
				});
		findViewById(R.id.sign_in_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						updateSelected(2);
					}
				});
		findViewById(R.id.sign_out_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						updateSelected(3);
					}
				});
	}

	private ArrayList<PopupEntity> getPopData() {
		ArrayList<PopupEntity> arrayList = new ArrayList<PopupEntity>();
		PopupEntity entity = new PopupEntity(R.drawable.icon_pop_chat,
				R.string.setting, 1);
		PopupEntity entity1 = new PopupEntity(R.drawable.icon_pop_newfriend,
				R.string.statistics, 2);
		arrayList.add(entity);
		arrayList.add(entity1);
		return arrayList;
	}

	/**
	 * 修改选中状态
	 *
	 * @param _type
	 *            1:外勤2:签到3：签退
	 */
	private void updateSelected(int _type) {
		if (_type == 1) {
			type = 1;
			fieldTv.setTextColor(getResources().getColor(
					R.color.the_main_color_normal));
			fieldIv.setImageResource(R.drawable.icon_feild_selected);
			signOutIv.setImageResource(R.drawable.icon_sign_out);
			signInIv.setImageResource(R.drawable.icon_sign_in);
			signOutTv.setTextColor(getResources().getColor(
					R.color.the_color_gray));
			signInTv.setTextColor(getResources().getColor(
					R.color.the_color_gray));
		} else if (_type == 2) {
			type = 1;
			signInTv.setTextColor(getResources().getColor(
					R.color.the_main_color_normal));
			signInIv.setImageResource(R.drawable.icon_sign_in_selected);
			signOutIv.setImageResource(R.drawable.icon_sign_out);
			fieldIv.setImageResource(R.drawable.icon_feild);
			signOutTv.setTextColor(getResources().getColor(
					R.color.the_color_gray));
			fieldTv.setTextColor(getResources()
					.getColor(R.color.the_color_gray));
		} else if (_type == 3) {
			type = 2;
			signOutTv.setTextColor(getResources().getColor(
					R.color.the_main_color_normal));
			signOutIv.setImageResource(R.drawable.icon_sing_out_selected);
			signInIv.setImageResource(R.drawable.icon_sign_in);
			fieldIv.setImageResource(R.drawable.icon_feild);
			signInTv.setTextColor(getResources().getColor(
					R.color.the_color_gray));
			fieldTv.setTextColor(getResources()
					.getColor(R.color.the_color_gray));
		}
	}

	private void getLoaction() {
		IMApplication.getInstance().GetBaiduLoacationUtil()
				.getGoogleLoaction(new IGetLocationListener() {

					@Override
					public void onSuccess(BDLocation location) {
						String url = "http://api.map.baidu.com/staticimage/v2?mcode=CC:B2:BA:B3:37:F2:3E:DD:33:E2:F0:F7:D2:C4:A4:D1:D3:18:F9:23;com.qyxim.qiyunxinim&ak=A6cG2cYEpepRRtVbcy7GZgkO&width=280&height=140&zoom=11&scale=2&center="
								+ location.getLongitude()
								+ ","
								+ location.getLatitude();
						position_tv.setText(location.getAddrStr());
						position_iv.SetUrl(url);
						latitude = location.getLatitude();
						longitude = location.getLongitude();
					}

					@Override
					public void onFail() {
					}
				});
	}

	private void playSound(String name, boolean isLoop) {
		if (BackgroundMediaPlayer == null) {
			BackgroundMediaPlayer = new MediaPlayer();
		}
		if (BackgroundMediaPlayer != null) {
			if (name.equalsIgnoreCase(soundName)) {
				if (!BackgroundMediaPlayer.isPlaying()) {
					BackgroundMediaPlayer.start();
				}
				return;
			}
			BackgroundMediaPlayer.stop();
			BackgroundMediaPlayer.reset();
			BackgroundMediaPlayer.setLooping(isLoop);

			AssetManager am = getAssets();
			try {
				AssetFileDescriptor afd = am.openFd(name);
				BackgroundMediaPlayer.setDataSource(afd.getFileDescriptor(),
						afd.getStartOffset(), afd.getLength());
				BackgroundMediaPlayer.prepare();
				BackgroundMediaPlayer.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		soundName = name;
	}

	@Override
	protected void onResume() {
		initShake();
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mShakeListener != null) {
			mShakeListener.stop();
			mShakeListener = null;
		}
		if (BackgroundMediaPlayer != null && BackgroundMediaPlayer.isPlaying()) {
			BackgroundMediaPlayer.pause();
		}
	}

	private void attendance() {
		mAttendanceHandle.addAttendance(entid + "", type, longitude + "",
				latitude + "", new AttendanceHandle.IAttendanceResultListener() {

					@Override
					public void onResult(int status, String msg) {

						if (status == HttpInvokeResultCode.RESULT_OK) {
							if (type == 1) {
								show();
							} else if (!TextUtils.isEmpty(msg)) {
								IMApplication.showToast(msg);
							}
						} else if (!TextUtils.isEmpty(msg)) {
							IMApplication.showToast(msg);
						}
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 100 && resultCode == RESULT_OK) {
			String url = "http://api.map.baidu.com/staticimage/v2?mcode=CC:B2:BA:B3:37:F2:3E:DD:33:E2:F0:F7:D2:C4:A4:D1:D3:18:F9:23;com.qyxim.qiyunxinim&ak=A6cG2cYEpepRRtVbcy7GZgkO&width=280&height=140&zoom=11&scale=2&center="
					+ data.getDoubleExtra("longitude", 0)
					+ ","
					+ data.getDoubleExtra("latitude", 0);
			position_iv.SetUrl(url);
			String address = data.getStringExtra("address");
			if (!TextUtils.isEmpty(address)) {
				position_tv.setText(address);
			}

			double[] la_lg = BaiDuMapUtil.baiduToGaode(
					data.getDoubleExtra("latitude", 0),
					data.getDoubleExtra("longitude", 0));
			// latitude = data.getDoubleExtra("latitude", 0);
			// longitude = data.getDoubleExtra("longitude", 0);
			latitude = la_lg[0];
			longitude = la_lg[1];

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void show() {
		AlphaAnimation aa = new AlphaAnimation(0.0f, 1.0f);// 创建一个AlphaAnimation
		aa.setDuration(1000);// 设置持续时间
		aa.setFillAfter(true);// 设置最后的动画效果，这里是显示状态（最后能够看到这个View)
		success_iv.startAnimation(aa);// 启动动画
		success_iv.setVisibility(View.VISIBLE);
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				gone();
			}
		}, 3000);

	}

	private void gone() {
		AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);// 创建一个AlphaAnimation
		aa.setDuration(1500);// 设置持续时间
		aa.setFillAfter(true);// 设置这个View最后的状态，由于是从1->0,所以最后的是消失状态（最后是看不到见这个View的）
		success_iv.startAnimation(aa);// 启动动画
		success_iv.setVisibility(View.GONE);
	}

}
